import Cookies from 'js-cookie'

const TOKEN_KEY = 'zenithmind_token'
const REFRESH_TOKEN_KEY = 'zenithmind_refresh_token'
const USER_INFO_KEY = 'zenithmind_user_info'

/**
 * 获取token
 */
export function getToken() {
  return Cookies.get(TOKEN_KEY) || localStorage.getItem(TOKEN_KEY)
}

/**
 * 设置token
 */
export function setToken(token, rememberMe = false) {
  if (rememberMe) {
    // 记住我，设置30天过期
    Cookies.set(TOKEN_KEY, token, { expires: 30 })
    localStorage.setItem(TOKEN_KEY, token)
  } else {
    // 会话token，浏览器关闭后过期
    Cookies.set(TOKEN_KEY, token)
    sessionStorage.setItem(TOKEN_KEY, token)
  }
}

/**
 * 移除token
 */
export function removeToken() {
  Cookies.remove(TOKEN_KEY)
  localStorage.removeItem(TOKEN_KEY)
  sessionStorage.removeItem(TOKEN_KEY)
}

/**
 * 获取刷新token
 */
export function getRefreshToken() {
  return Cookies.get(REFRESH_TOKEN_KEY) || localStorage.getItem(REFRESH_TOKEN_KEY)
}

/**
 * 设置刷新token
 */
export function setRefreshToken(refreshToken, rememberMe = false) {
  if (rememberMe) {
    Cookies.set(REFRESH_TOKEN_KEY, refreshToken, { expires: 30 })
    localStorage.setItem(REFRESH_TOKEN_KEY, refreshToken)
  } else {
    Cookies.set(REFRESH_TOKEN_KEY, refreshToken)
    sessionStorage.setItem(REFRESH_TOKEN_KEY, refreshToken)
  }
}

/**
 * 移除刷新token
 */
export function removeRefreshToken() {
  Cookies.remove(REFRESH_TOKEN_KEY)
  localStorage.removeItem(REFRESH_TOKEN_KEY)
  sessionStorage.removeItem(REFRESH_TOKEN_KEY)
}

/**
 * 获取用户信息
 */
export function getUserInfo() {
  try {
    const userInfo = localStorage.getItem(USER_INFO_KEY) || sessionStorage.getItem(USER_INFO_KEY)
    return userInfo ? JSON.parse(userInfo) : null
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

/**
 * 设置用户信息
 */
export function setUserInfo(userInfo, rememberMe = false) {
  const userInfoStr = JSON.stringify(userInfo)
  if (rememberMe) {
    localStorage.setItem(USER_INFO_KEY, userInfoStr)
  } else {
    sessionStorage.setItem(USER_INFO_KEY, userInfoStr)
  }
}

/**
 * 移除用户信息
 */
export function removeUserInfo() {
  localStorage.removeItem(USER_INFO_KEY)
  sessionStorage.removeItem(USER_INFO_KEY)
}

/**
 * 清除所有认证信息
 */
export function clearAuth() {
  removeToken()
  removeRefreshToken()
  removeUserInfo()
}

/**
 * 检查token是否过期
 */
export function isTokenExpired(token) {
  if (!token) return true
  
  try {
    // 解析JWT token
    const payload = JSON.parse(atob(token.split('.')[1]))
    const currentTime = Math.floor(Date.now() / 1000)
    
    // 检查是否过期（提前5分钟判断为过期）
    return payload.exp < (currentTime + 300)
  } catch (error) {
    console.error('解析token失败:', error)
    return true
  }
}

/**
 * 获取token剩余时间（秒）
 */
export function getTokenRemainingTime(token) {
  if (!token) return 0
  
  try {
    const payload = JSON.parse(atob(token.split('.')[1]))
    const currentTime = Math.floor(Date.now() / 1000)
    return Math.max(0, payload.exp - currentTime)
  } catch (error) {
    console.error('解析token失败:', error)
    return 0
  }
}

/**
 * 检查是否已登录
 */
export function isLoggedIn() {
  const token = getToken()
  return token && !isTokenExpired(token)
}

/**
 * 检查用户权限
 */
export function hasPermission(permission) {
  const userInfo = getUserInfo()
  if (!userInfo || !userInfo.permissions) return false
  
  return userInfo.permissions.includes(permission)
}

/**
 * 检查用户角色
 */
export function hasRole(role) {
  const userInfo = getUserInfo()
  if (!userInfo || !userInfo.roles) return false
  
  return userInfo.roles.includes(role)
}

/**
 * 检查是否有任一权限
 */
export function hasAnyPermission(permissions) {
  if (!Array.isArray(permissions)) return false
  
  const userInfo = getUserInfo()
  if (!userInfo || !userInfo.permissions) return false
  
  return permissions.some(permission => userInfo.permissions.includes(permission))
}

/**
 * 检查是否有任一角色
 */
export function hasAnyRole(roles) {
  if (!Array.isArray(roles)) return false
  
  const userInfo = getUserInfo()
  if (!userInfo || !userInfo.roles) return false
  
  return roles.some(role => userInfo.roles.includes(role))
}

/**
 * 检查是否有所有权限
 */
export function hasAllPermissions(permissions) {
  if (!Array.isArray(permissions)) return false
  
  const userInfo = getUserInfo()
  if (!userInfo || !userInfo.permissions) return false
  
  return permissions.every(permission => userInfo.permissions.includes(permission))
}

/**
 * 检查是否有所有角色
 */
export function hasAllRoles(roles) {
  if (!Array.isArray(roles)) return false
  
  const userInfo = getUserInfo()
  if (!userInfo || !userInfo.roles) return false
  
  return roles.every(role => userInfo.roles.includes(role))
}

/**
 * 获取用户ID
 */
export function getUserId() {
  const userInfo = getUserInfo()
  return userInfo ? userInfo.id : null
}

/**
 * 获取用户名
 */
export function getUsername() {
  const userInfo = getUserInfo()
  return userInfo ? userInfo.username : null
}

/**
 * 获取用户头像
 */
export function getUserAvatar() {
  const userInfo = getUserInfo()
  return userInfo ? userInfo.avatar : null
}

/**
 * 获取用户邮箱
 */
export function getUserEmail() {
  const userInfo = getUserInfo()
  return userInfo ? userInfo.email : null
}

/**
 * 格式化权限列表
 */
export function formatPermissions(permissions) {
  if (!Array.isArray(permissions)) return []
  
  return permissions.map(permission => ({
    code: permission,
    name: getPermissionName(permission)
  }))
}

/**
 * 获取权限名称
 */
export function getPermissionName(permission) {
  const permissionMap = {
    'user:read': '查看用户',
    'user:write': '编辑用户',
    'user:delete': '删除用户',
    'course:read': '查看课程',
    'course:write': '编辑课程',
    'course:delete': '删除课程',
    'exam:read': '查看考试',
    'exam:write': '编辑考试',
    'exam:delete': '删除考试',
    // 更多权限映射...
  }
  
  return permissionMap[permission] || permission
}

/**
 * 格式化角色列表
 */
export function formatRoles(roles) {
  if (!Array.isArray(roles)) return []
  
  return roles.map(role => ({
    code: role,
    name: getRoleName(role)
  }))
}

/**
 * 获取角色名称
 */
export function getRoleName(role) {
  const roleMap = {
    'admin': '管理员',
    'teacher': '教师',
    'student': '学生',
    'author': '作者',
    'editor': '编辑',
    // 更多角色映射...
  }
  
  return roleMap[role] || role
}
